package com.atguigu.lease.web.admin.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
//        targerType 相当于枚举子类
//        todo 1 、前端的type是字符串类型，需要转换成枚举类型
//        todo 2、通过反射拿到枚举类里的属性
        Converter converter = (source)->{
            T[] enumConstants = targetType.getEnumConstants();
//        todo 3、 判断枚举类的属性是否为空，不为空就遍历返回属性
            if(enumConstants != null && enumConstants.length > 0){
                for (T enumConstant : enumConstants) {
//       todo 4、转换枚举类的类型为string和前端传来的类型进行比较  如果一致就返回枚举类的属性
                    if(source.equals(String.valueOf(enumConstant.getCode()))){
                        return enumConstant;
                    }
                }
            }
            return null;
        };
        return converter;
    }
}
